/**
 * Filename: AlbumStatusAdapter.java
 *
 * @author Firefly
 * @contact postfirefly@163.com
 * @time 2016/3/6 15:05
 */
package com.github.postsanf.yinian.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.activity.BrowseActivity;
import com.github.postsanf.yinian.activity.MemoryCardDetailActivity;
import com.github.postsanf.yinian.activity.SharePhotoActivity;
import com.github.postsanf.yinian.activity.StatusDetailActivity;
import com.github.postsanf.yinian.activity.StatusShareActivity;
import com.github.postsanf.yinian.activity.UserStatusActivity;
import com.github.postsanf.yinian.bean.YNStatus;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.constants.YNSingleton;
import com.github.postsanf.yinian.randomlayout.DividerItemDecoration;
import com.github.postsanf.yinian.randomlayout.TwoWayView;
import com.github.postsanf.yinian.service.DoLikeService;
import com.github.postsanf.yinian.twowayview.ItemClickSupport;
import com.github.postsanf.yinian.utils.DisplayUtils;
import com.github.postsanf.yinian.utils.ImageOptHelper;
import com.github.postsanf.yinian.utils.StringUtils;
import com.github.postsanf.yinian.utils.TimeUtils;
import com.github.postsanf.yinian.utils.UIHelper;
import com.github.postsanf.yinian.utils.YNInviteSecret;
import com.github.postsanf.yinian.utils.YNUrlHelper;
import com.github.postsanf.yinian.view.StyleDialog;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class AlbumStatusAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private int adapterPage = 0;// 0 普通相册页面、1 官方相册页面、2 我的页面、3 成员信息页面
    private Context context;
    private List<YNStatus> mDatas;
    private ImageLoader mImageLoader;
    private OnItemClickListener mListener;
    public static HashMap<Integer, Boolean> isLike = new HashMap<Integer, Boolean>();
    private boolean isInAlbum = false;
    private static final int EMPTY_VIEW = 10;
    private AlbumStatusGridLayoutAdapter mGridAdapter;

    public List<YNStatus> getDatas() {
        return mDatas;
    }

    public void setDatas(List<YNStatus> datas) {
        mDatas = datas;
    }

    public boolean isInAlbum() {
        return isInAlbum;
    }

    public void setIsInAlbum(boolean isInAlbum) {
        this.isInAlbum = isInAlbum;
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.mListener = listener;
    }

    public AlbumStatusAdapter(Context context, List<YNStatus> mDatas, int adapterPage) {
        this.context = context;
        this.mDatas = mDatas;
        this.adapterPage = adapterPage;
        mImageLoader = ImageLoader.getInstance();
    }

    public class EmptyViewHolder extends RecyclerView.ViewHolder {
        public EmptyViewHolder(View itemView) {
            super(itemView);
        }
    }

    public class ViewHolder extends RecyclerView.ViewHolder {


        TwoWayView twoways_view;
        RelativeLayout rl_status_top;
        // 头部 - 相册页面
        LinearLayout ll_status_album;
        SimpleDraweeView status_user_avatar;
        TextView status_user_name;
        // 头部 - 我的页面
        LinearLayout ll_status_me;
        TextView status_album_name;
        // 内容部分
        LinearLayout ll_status_bottom;
        TextView status_submit_time;
        LinearLayout ll_status_content;
        TextView tv_status_content;
        LinearLayout ll_status_like;
        CheckBox cb_status_like;
        TextView tv_like_num;
        LinearLayout ll_status_comment;
        TextView tv_comment_num;
        LinearLayout ll_status_share;

        RelativeLayout item_memorycard;
        SimpleDraweeView item_memorycardpic;
        TextView item_memorytime;
        TextView item_memorylocation;
        RelativeLayout rl_include_status_twoways;

        public ViewHolder(View itemView) {
            super(itemView);
            twoways_view = (TwoWayView) itemView.findViewById(R.id.twoways_view);
            rl_status_top = (RelativeLayout) itemView.findViewById(R.id.rl_status_top);
            ll_status_album = (LinearLayout) itemView.findViewById(R.id.ll_status_album);
            status_user_avatar = (SimpleDraweeView) itemView.findViewById(R.id.status_user_avatar);
            status_user_name = (TextView) itemView.findViewById(R.id.status_user_name);
            ll_status_me = (LinearLayout) itemView.findViewById(R.id.ll_status_mypage);
            status_album_name = (TextView) itemView.findViewById(R.id.status_album_name);
            ll_status_bottom = (LinearLayout) itemView.findViewById(R.id.ll_status_bottom);
            status_submit_time = (TextView) itemView.findViewById(R.id.status_submit_time);
            ll_status_content = (LinearLayout) itemView.findViewById(R.id.ll_status_content);
            tv_status_content = (TextView) itemView.findViewById(R.id.tv_status_content);
            ll_status_like = (LinearLayout) itemView.findViewById(R.id.ll_status_like);
            cb_status_like = (CheckBox) itemView.findViewById(R.id.cb_status_like);
            tv_like_num = (TextView) itemView.findViewById(R.id.tv_like_num);
            ll_status_comment = (LinearLayout) itemView.findViewById(R.id.ll_status_comment);
            tv_comment_num = (TextView) itemView.findViewById(R.id.tv_comment_number);
            ll_status_share = (LinearLayout) itemView.findViewById(R.id.ll_status_share);

            //记录卡片
            item_memorycard = ((RelativeLayout) itemView.findViewById(R.id.item_memorycard));
            item_memorycardpic = ((SimpleDraweeView) itemView.findViewById(R.id.item_memorycardpic));
            item_memorytime = ((TextView) itemView.findViewById(R.id.item_memorytime));
            item_memorylocation = (TextView) itemView.findViewById(R.id.item_memorylocation);
            rl_include_status_twoways = ((RelativeLayout) itemView.findViewById(R.id.rl_include_status_twoways));
        }

        public void bindData(final YNStatus item) {
            if (item != null) {
                switch (adapterPage) {
                    case 0:
                        ll_status_album.setVisibility(View.VISIBLE);
                        String avatarPaths = YNUrlHelper.getAvatarUrl(context, item.getPublishUser().getUpic());
                        Uri avatarUri = Uri.parse(avatarPaths);
                        ImageOptHelper.showFrescoAvatar(avatarUri, status_user_avatar, context);
                        status_user_name.setText(item.getPublishUser().getUnickname());
                        ll_status_album.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Intent intent = new Intent(context, UserStatusActivity.class);
                                intent.putExtra(CommonConstants.YNUSERID, item.getPublishUser().getUserid());
                                intent.putExtra(CommonConstants.YNGROUPID, YNSingleton.getInstance().getCurAlbum().getGroupid());
                                context.startActivity(intent);
                            }
                        });
                        break;
                    // 官方相册
                    case 1:
                        ll_status_album.setVisibility(View.VISIBLE);
                        String gavatarPaths = YNUrlHelper.getAvatarUrl(context, item.getPublishUser().getUpic());
                        Uri gavatarUri = Uri.parse(gavatarPaths);
                        ImageOptHelper.showFrescoAvatar(gavatarUri, status_user_avatar, context);
                        status_user_name.setText(item.getPublishUser().getUnickname());
                        ll_status_like.setVisibility(View.VISIBLE);
                        cb_status_like.setChecked(item.getLislike() == 1);
                        tv_like_num.setText(StringUtils.numberToStr(item.getElike()));
                        //记录卡片
                        if (item.getEtype() == 1) {
                            rl_include_status_twoways.setVisibility(View.GONE);
                            List<String> sslist = item.getThumbnail();
                            item_memorycard.setVisibility(View.VISIBLE);
                            item_memorycard.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, UIHelper.getHigh(context) + UIHelper.dip2px(context, 100)));
                            String paths = YNUrlHelper.getStatusUrl(context, sslist.get(0));
                            ImageOptHelper.showFrescoStatus(Uri.parse(StringUtils.repaceImgUrl(paths)), item_memorycardpic, context);
                            String mtime = item.getEmemorytime();
                            item_memorytime.setText("发生于" + mtime.split(" ")[0]);
                            if (!StringUtils.isEmpty(item.getEplace())) {
                                if (item.getEplace().length() > 8) {
                                    item_memorylocation.setText(item.getEplace().substring(0, 7) + "...");
                                } else {
                                    item_memorylocation.setText(item.getEplace());
                                }
                            } else {
                                item_memorylocation.setText("忆年");
                            }
                            item_memorycard.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    YNSingleton.getInstance().setCurStatus(item);
                                    context.startActivity(new Intent(context, MemoryCardDetailActivity.class));
                                }
                            });
                        }
                        break;
                    // 我的页面
                    case 2:
                        ll_status_me.setVisibility(View.VISIBLE);
                        status_album_name.setText(item.getGname());
                        break;
                    // 成员页面
                    case 3:
                        rl_status_top.setVisibility(View.GONE);
                        break;
                }
//                status_submit_time.setText(TimeUtils.getGroupStatusTime(item.getEuploadtime()));
//                Log.d("yuhao", TimeUtils.getGroupStatusTime(item.getEuploadtime()));
//                status_submit_time.setText(item.getEuploadtime());
                //判断时间显示是否有问题
                if (TimeUtils.getGroupStatusTime(item.getEuploadtime()).contains("HH")) {
                    //时间显示有问题出现字母用此方法显示时间
                    status_submit_time.setText(TimeUtils.getUpLoadTime(item.getEuploadtime()));
                } else {
                    status_submit_time.setText(TimeUtils.getGroupStatusTime(item.getEuploadtime()));
                }
                if (item.getEtext() != null && item.getEtext().length() > 0) {
                    ll_status_content.setVisibility(View.VISIBLE);
                    tv_status_content.setText(item.getEtext());
                } else {
                    ll_status_content.setVisibility(View.GONE);
                }

                ll_status_comment.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (!isInAlbum) {
                            return;
                        }
                        // 点击了评论按钮 页面跳转
                        YNSingleton.getInstance().setCurStatus(item);
                        Intent intent = new Intent(context, StatusDetailActivity.class);
                        intent.putExtra("adapterPage", adapterPage);
                        context.startActivity(intent);
                    }
                });
                ll_status_share.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // TODO:跳转页面选择分享图片
                        if (item.getEtype() == 1) {
                            StyleDialog styleDialog = new StyleDialog(context);
                            styleDialog.setCanceledOnTouchOutside(true);
                            styleDialog.show();
                            styleDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                                @Override
                                public void onDismiss(DialogInterface dialog) {
                                    SharedPreferences sp = context.getSharedPreferences("isApart", Context.MODE_PRIVATE);
                                    int isApart = sp.getInt("isApart", 0);
                                    if (isApart == 1) {
                                        Intent intent = new Intent(context, SharePhotoActivity.class);
                                        intent.putStringArrayListExtra(ACTIONs.aAddData, (ArrayList<String>) item.getUrl());
                                        context.startActivity(intent);
                                    } else if (isApart == 2) {
                                        String url = context.getResources().getString(R.string.SHARE_JIYI);
                                        String sec = null;
                                        try {
                                            sec = YNInviteSecret.encryptDES("eventid=" + item.getEid(), context.getResources().getString(R.string.UNKNOW_ID));
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                        url = url + sec;
                                        String avatarPaths = YNUrlHelper.getAvatarUrl(context, item.getPublishUser().getUpic());
                                        Intent intent = new Intent(context, StatusShareActivity.class);
                                        intent.putExtra("share", "share");
                                        intent.putExtra("avatarPaths", avatarPaths);
                                        intent.putExtra("fristpic", item.getUrl().get(0));
                                        intent.putExtra("title", item.getPublishUser().getUnickname() + "。" + "有一段美好的时光@你！");
                                        intent.putExtra("desc", "秘密花园限时开放哦！");
                                        intent.putExtra("url", url);
                                        context.startActivity(intent);
                                    }
                                    SharedPreferences.Editor edit = sp.edit();
                                    edit.putInt("isApart", 0);
                                    edit.commit();
                                }
                            });
                        } else {
                            Intent intent = new Intent(context, SharePhotoActivity.class);
                            intent.putStringArrayListExtra(ACTIONs.aAddData, (ArrayList<String>) item.getUrl());
                            context.startActivity(intent);
                        }
                    }
                });

                tv_comment_num.setText(StringUtils.numberToStr((item.getComments() == null || item.getComments().size() == 0) ? 0 : item.getComments().size()));
                final ItemClickSupport itemClick = ItemClickSupport.addTo(twoways_view);
                itemClick.setOnItemClickListener(new ItemClickSupport.OnItemClickListener() {
                    @Override
                    public void onItemClick(RecyclerView parent, View child, int position, long id) {
                        YNSingleton.getInstance().setCurStatus(item);
                        Intent intent = new Intent(context, BrowseActivity.class);
                        // 若是我的页面则附带参数
                        if (2 == adapterPage) {
                            intent.putExtra(CommonConstants.YNISME, true);
                        }
                        intent.putExtra(CommonConstants.YNPOSITION, position);
                        intent.putExtra("type", "time");
                        context.startActivity(intent);
                    }
                });

                twoways_view.setScrollContainer(false);
                twoways_view.setKeepScreenOn(false);

                final Drawable divider = context.getResources().getDrawable(R.drawable.divider);
                twoways_view.addItemDecoration(new DividerItemDecoration(divider));
                mGridAdapter = new AlbumStatusGridLayoutAdapter(context, twoways_view, item.getThumbnail());
                twoways_view.setAdapter(mGridAdapter);
            }
        }
    }

    private YNStatus getItem(int position) {
        return mDatas.get(position);
    }

    // 创建ViewHolder
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == EMPTY_VIEW) {
            int resId = R.layout.yn_empty_status;
            switch (adapterPage) {
                case 3:
                    resId = R.layout.yn_empty_member_status;
                    break;
                default:
                    break;
            }
            View v = LayoutInflater.from(parent.getContext()).inflate(resId, parent, false);
            v.getRootView().getLayoutParams().height = DisplayUtils.getScreenHeightPixels((Activity) context) - DisplayUtils.dp2px(context, 210);
            return new EmptyViewHolder(v);
        }
        final View convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.yn_include_album_status_item, parent, false);
        convertView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mListener != null) {
                    mListener.OnItemClick(v, (YNStatus) convertView.getTag());
                }
            }
        });
        return new ViewHolder(convertView);
    }

    // 绑定数据到View
    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder rv_holder, final int position) {
        if (rv_holder instanceof ViewHolder) {
            final ViewHolder holder = (ViewHolder) rv_holder;
            holder.setIsRecyclable(false);
            final YNStatus item = getItem(position);
            holder.bindData(item);
            // 进入官方相册保存点赞状态
            if (1 == adapterPage) {
                isLike.put(position, 1 == item.getLislike());
                holder.cb_status_like.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (!isInAlbum) {
                            return;
                        }
                        boolean isChecked = holder.cb_status_like.isChecked();
                        item.setLislike(isChecked ? 1 : 0);
                        isLike.put(position, isChecked);
                        if (isChecked) {
                            todoLike(String.valueOf(item.getEid()), "like");
                            item.setElike(item.getElike() + 1);
                        } else {
                            todoLike(String.valueOf(item.getEid()), "unlike");
                            if (item.getElike() > 0) {
                                item.setElike(item.getElike() - 1);
                            }
                        }
                        holder.tv_like_num.setText(StringUtils.numberToStr(item.getElike()));
                    }
                });
                boolean res;
                if (isLike.get(position) == null || !isLike.get(position)) {
                    res = false;
                    isLike.put(position, false);
                } else {
                    res = true;
                }
                holder.cb_status_like.setChecked(res);
            }
            holder.itemView.setTag(item);
        }
    }

    private void todoLike(String eid, String type) {
        Intent mIntent = new Intent(context, DoLikeService.class);
        mIntent.setAction(ACTIONs.actionDoLick);
        mIntent.putExtra(ACTIONs.aLoadId, eid);
        mIntent.putExtra(ACTIONs.aNeedType, type);
        context.startService(mIntent);
    }

    @Override
    public int getItemViewType(int position) {
        if (mDatas.size() == 0) {
            return EMPTY_VIEW;
        }
        return super.getItemViewType(position);
    }

    @Override
    public int getItemCount() {
        return mDatas.size() > 0 ? mDatas.size() : 1;
    }

    public void addItemsFromTop(List<YNStatus> items) {
        if (items == null)
            return;
        this.mDatas.addAll(0, items);
        this.notifyItemRangeInserted(0, items.size());
    }

    public void addItemsFromTopOne(YNStatus items) {
        if (items == null)
            return;
        this.mDatas.add(0, items);
        this.notifyItemRangeInserted(0, 1);
    }

    public void removeOne(int ids) {
        for (int i = 0; i < mDatas.size(); i++) {
            if (ids == mDatas.get(i).getEid()) {
                this.mDatas.remove(i);
                this.notifyItemRemoved(i);
                break;
            }
        }
    }

    public void SyncComment() {
        for (int i = 0; i < mDatas.size(); i++) {
            if (mDatas.get(i).getEid() == YNSingleton.getInstance().getCurStatus().getEid()) {
                mDatas.get(i).setComments(YNSingleton.getInstance().getCurStatus().getComments());
                AlbumStatusAdapter.this.notifyDataSetChanged();
            }
        }
    }

    public void addItemsFromBottom(List<YNStatus> items) {
        if (items == null)
            return;
        this.mDatas.addAll(mDatas.size(), items);
        this.notifyItemRangeInserted(mDatas.size(), items.size());
    }

    public interface OnItemClickListener {
        public void OnItemClick(View view, YNStatus data);
    }

    public int getIdByDirection(boolean isTop) {
        if (isTop) {
            if (mDatas.size() <= 0) {
                return 0;
            }
            return mDatas.get(0).getEid();
        } else {
            if (mDatas.size() <= 0) {
                return 0;
            }
            return mDatas.get(mDatas.size() - 1).getEid();
        }
    }
}
